//
//  MeSetUsetImg.m
//  OC_Poj_demo
//
//  Created by weixin on 2018/7/20.
//  Copyright © 2018年 weixn. All rights reserved.
//

#import "MeSetUsetImg.h"
#import "TZImagePickerController.h"
#import "NetworkEngine.h"
#import "NetworkEngine+imageCloudManager.h"


#define kURL_UpdateInfo @"/app/user/updateInfo"


@interface MeSetUsetImg ()< UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, TZImagePickerControllerDelegate>
@property (nonatomic,strong)UIScrollView * sv;
@property (nonatomic,strong)UIImageView * lastImg;
@end

@implementation MeSetUsetImg

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setNav];
    
    [self setUI];
    
    [self loeddata];
    
    
    
}


-(void)loeddata{
    @weakify(self);
    [[AccountService loadgetSystemAvatar:@"1"]subscribeNext:^(ResponseData  * x) {
        @strongify(self);
        
        if (x.success) {
            NSArray *arr = x.responseRawData[@"data"];
            NSMutableArray *arrM = [[NSMutableArray alloc]init];
            
            for (NSDictionary *dic in arr) {
                NSString *str = [NSString stringWithFormat:@"%@%@",RootUrlImage,dic[@"filePath"]];
                [arrM addObject:str];
            }
            
            CGFloat imgHeight = (SCREEN_WIDTH-100)/3;

            for (int i = 0; i<arrM.count; i++) {
                
                UIImageView *imageV = [[UIImageView alloc]initWithFrame:
                                       CGRectMake(70/4+i%3*(imgHeight+100/3), i/3*(imgHeight+30)+20, imgHeight, imgHeight)];
                imageV.contentMode = 2;
                imageV.alpha = 0.5;
                imageV.tag = i+100;
                [imageV setShadowType1WithColor:[UIColor colorWithHex:@"#E8E9EC"] offset:CGSizeZero opacity:1 radius:3];
                
                [self.sv addSubview:imageV];
                
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
                
                [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
                    UIImageView *image =(UIImageView*)x.view ;
                    [UIView animateWithDuration:0.4 animations:^{
                        
                        [self animateWithDuration:image];
                    }];
                }];
                [imageV addGestureRecognizer:tap];
                imageV.userInteractionEnabled = YES;
                
                NSLog(@"%@",[NSURL URLWithString:arrM[i]]);
                [imageV sd_setImageWithURL:[NSURL URLWithString:arrM[i]] placeholderImage:nil];
                [imageV setCornerRadiusWithRadius:imgHeight/2.0 isMasks:YES];
                imageV.clipsToBounds = YES;
                
            }
            
//            if
            
            self.sv.contentSize = CGSizeMake(0, arrM.count/3*(imgHeight+30)+20);
        }else{
             [Tools showTips:x.errorInfo];
        }

    }];
    
}

-(void)setNav{
    
    
    [self.baseNavigationView setHiddenNav:NO VC:self];

    /* TODO: ================= 导航栏V4样式 =================*/
    [self.baseNavigationView NavigationBarStyle:1];
    self.baseNavigationView.leftButton1.hidden = YES;
 

    
}


-(void)setUI{
    

    [self.view addSubview:self.sv];
    
    self.imgBtn.frame = CGRectMake(kScreenW/2.0,kScreenH-100,kScreenW/2.0, 100);
    self.cancelBtn.frame = CGRectMake(0,kScreenH-100,kScreenW/2.0, 100);
    
    BaseView *view = [[BaseView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        make.bottom.equalTo(self.view).offset(0);
        make.height.mas_equalTo(60+kBottomSafeHeight);
    }];
    
    
    BaseBtn *btn = [[BaseBtn alloc]initializeFrame:CGRectMake(0, 0, 1, 1) NormalText:@"确定" NormalTextColor:baseColorTheme SeleText:@"确定" SeleTextColor:baseColorTheme font:15 isBold:NO];
    btn.backgroundColor = [UIColor whiteColor];
    [btn setCornerRadiusWithRadius:8 isMasks:YES];
    [btn setBorderWithColor:baseColorTheme width:1];
    [self.view addSubview:btn];
    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.right.equalTo(self.view).offset(-15);
        make.bottom.equalTo(self.view).offset(-8-kBottomSafeHeight);
        make.height.mas_equalTo(44);
    }];
    
    @weakify(self);
    [[btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self);
        /* TODO: ================= 上传用户头像 =================*/
        if (self.lastImg.image != nil) {
            //上传腾讯云服务器上
            [kNetworkShared getImageURLWithImage:self.lastImg.image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                
                if (isSuccess) {
                    
                    NSString * avatar = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
                    NSLog(@"");
                    @weakify(self);
                    [[AccountService loadsaveUserAvatar:avatar]subscribeNext:^(ResponseData *x) {
                        @strongify(self);
                        if (x.success) {
                            //更新用户数据
                            kUSER_INFO_MANAGER.avatar = avatar;
                            [kUSER_INFO_MANAGER MyList];
                            if (self.block) {
                                self.block();
                            }
                            [self.navigationController popViewControllerAnimated:YES];
                            [QMUITips  showSucceed:@"修改成功"];
                        }else{
                             [Tools showTips:x.errorInfo];
                        }
                        
                    }];
                }else{
                    [Tools showTips:@"上传失败"];
                }
                
            }];
        }else{
            [Tools showTips:@"请选择头像"];
        }
    }];
}



//动画解析
-(void)animateWithDuration:(UIImageView *)image{
    NSLog(@"");
    if (![self.lastImg isEqual:image]) {
        
        [image setBorderWithColor:baseColorTheme width:2];
        image.alpha = 1;
        [self.lastImg setBorderWithColor:[UIColor clearColor] width:1];
        self.lastImg.alpha = 0.5;

        
        //放大点击  还原原来的
        self.lastImg.bounds = image.bounds;
        [self.lastImg setCornerRadiusWithRadius:image.bounds.size.width/2.0 isMasks:YES];
        CGRect Rect =  image.bounds;
        Rect.size.height = Rect.size.height*1.3;
        Rect.size.width = Rect.size.width*1.3;
        image.bounds = Rect;
        [image setCornerRadiusWithRadius:Rect.size.width/2.0 isMasks:YES];
        self.lastImg = image;

        /* TODO: ================= 四周放大  原来还原 =================*/

    }
  
}

-(UIScrollView *)sv{
    if (!_sv) {
        _sv = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NaviHeight, SCREEN_WIDTH, SCREEN_HEIGHT-NaviHeight-60-kBottomSafeHeight)];
        _sv.directionalLockEnabled = YES;
        _sv.alwaysBounceHorizontal = YES;
        _sv.alwaysBounceVertical = YES;
        _sv.showsHorizontalScrollIndicator = NO;
        _sv.showsVerticalScrollIndicator = NO;
        _sv.bounces = NO;
        _sv.decelerationRate = 0.1; // 值域 0~1 值越小减速停止的时间越短
        _sv.pagingEnabled = NO;

    }
    return _sv;
}

- (IBAction)censer:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)done:(id)sender {
 
}

/* MARK: ================= 上传用户头像图片 =================*/
#pragma mark - 打开图片浏览器
-(void)presentImagePicker{
    TZImagePickerController *picker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    picker.allowPickingVideo = NO;
    picker.allowTakeVideo = NO;
    __weak __typeof(self)weakSelf = self;
    [picker setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        if (photos.count > 0) {
            /* TODO: ================= 添加等待图标 =================*/

            // 添加了图片 先上传到服务器
            UIImage *image = photos.firstObject;
            
            //上传腾讯云服务器上
            [kNetworkShared getImageURLWithImage:image completion:^(COSObjectUploadTaskRsp *uploadTaskRsp, NSString *filePath, NSString *fileName, BOOL isSuccess, NSError *error) {
                
                
                NSString * avatar = kSTRING_FORMAT(@"%@/%@",filePath,fileName);
                NSDictionary *dic = @{@"token":kUSER_INFO_MANAGER.token,@"avatar":avatar,@"id":kUSER_INFO_MANAGER.userId};
            }];
        }
    }];
}


@end
